import React,{ Component } from 'react'
import {
    Button,
    Row,
    Col,
    Input,
    InputNumber,
    Collapse,
    message,
} from 'antd';
import { LegionsProForm,LegionsProConditions, LegionsProModal } from 'legions-pro-design';
import { bind,observer } from 'legions/store-react'
import ProjectStore from '../../stores/projectStore';
import { PropertyQueryFormFields, PropertyQuerySearchFields } from '../../models/form/propertyQueryFormFields';
import QueryConditionsPropertyConfig from '../../components/property.config.table/queryConditionsPropertyConfig';
import { observable, runInAction } from 'mobx'
import { fullProvider,lazyInject,inject } from 'legions-control-container';
import AddSelectOptions from '../components.widget/addSelectOptions';
import { ISelectAutoQuery } from 'legions-pro-design/es/LegionsStoreConditions/interface';
import { getExecutableScript, transformFuncToExeccodeast } from '../../utils/codemodCore';
import { transformTableToekn } from '../../utils/codemod';
import has from 'lodash/has';
import get from 'lodash/get';
import * as recast from 'recast';
import { EditCodeEnum } from '../../components/property.config.table/tableListPropertyConfig';
import { tableAutoQueryEnumMapp, TableListViewDomain, TABLE_COLUMNS_ENUM_MAPP } from '../../services/components/tableListViewDomain';
import CodeEditor from '../../components/codeEditor';
import { InstanceProModal } from 'legions-pro-design/es/LegionsProModal/interface';
const serialize = require('serialize-javascript');
interface IProps {
    store?: ProjectStore
}
const { Panel } = Collapse;
@bind({ store: ProjectStore })
@observer
export default class TableQueryParamsProperty extends Component<IProps> {
    @lazyInject(QueryConditionsPropertyConfig)
    queryConditionsPropertyConfig!: QueryConditionsPropertyConfig;
    codeModalRef: InstanceProModal = null;
    @observable code = '';
    @observable editConfigParameter: keyof typeof TableListViewDomain.tableAutoQuerystaticMember = null;
    constructor(props: IProps) {
        super(props);
    }
    createQueryConditionsPropertyConfig = () => {
        return this.queryConditionsPropertyConfig.createQueryConditionsPropertyConfig(this)
    }
    createQuerySearchPropertyConfig = () => {
        return this.queryConditionsPropertyConfig.createQuerySearchPropertyConfig(this)
    }
    updateTableCodeValue(values: string) {
        const value = {};
        const QueryPropertyApp = this.props.store.context.listPagePropertyApp.context.QueryPropertyApp;
        const keys = EditCodeEnum[this.editConfigParameter];
        value[this.editConfigParameter] = { value: values };
        if (tableAutoQueryEnumMapp[keys]) {
            QueryPropertyApp.querySearchFormProperyRef.store.updateFormInputData(QueryPropertyApp.querySearchFormProperyRef.uid,value);
        }
        if (this.editConfigParameter === 'onQuerySearch') {
            QueryPropertyApp.queryComponentRef.methods.setFieldsValues('search',(value) => {
                //@ts-ignore
                value.conditionsProps['onSearchExec'] = values;
                value.conditionsProps['onSearch'] = this.execcodeast('onSearch',values);
            })
        }
        if (this.editConfigParameter === 'onQueryReset') {
            QueryPropertyApp.queryComponentRef.methods.setFieldsValues('search',(value) => {
                value.conditionsProps['onResetExec'] = values;
                //@ts-ignore
                value.conditionsProps['onReset'] = this.execcodeast('onReset',values);
            })
        }
    }
    handleEditCode = (value: (typeof EditCodeEnum)[keyof typeof EditCodeEnum]) => { 
        const QueryPropertyApp = this.props.store.context.listPagePropertyApp.context.QueryPropertyApp;
        const viewModel: PropertyQuerySearchFields = QueryPropertyApp.querySearchFormProperyRef.viewModel.InputDataModel as PropertyQuerySearchFields;
        const valuesMapp = TableListViewDomain.tableAutoQuerystaticMember[tableAutoQueryEnumMapp[value]];
        runInAction(() => {
            this.editConfigParameter = tableAutoQueryEnumMapp[value];
            this.codeModalRef.viewModel.title = valuesMapp['label'];
            this.code = viewModel[tableAutoQueryEnumMapp[value]]['value'] || valuesMapp['value'];
            this.codeModalRef.viewModel.visible = true;
            const width = 960;
            this.codeModalRef.viewModel.width = width;
        })
    }
    execcodeast = (name: string,value:string) => {
        const TablePropertyApp = this.props.store.context.listPagePropertyApp.context.TablePropertyApp;
        const receiveValue = 'this.props.store.context.listPagePropertyApp.context.TablePropertyApp';
        const code= transformFuncToExeccodeast(value,{
            propertyName: name,
            receiveValue: `${receiveValue}.viewModel.paramesExeccodeast`,
        });
        eval(getExecutableScript(code,this));
        return TablePropertyApp.viewModel.paramesExeccodeast[name]
    }
    render() {
        const QueryPropertyApp = this.props.store.context.listPagePropertyApp.context.QueryPropertyApp;
        const TablePropertyApp = this.props.store.context.listPagePropertyApp.context.TablePropertyApp;
        return (
            <div>
                <Collapse defaultActiveKey={['1','2']}>

                    <Panel header="搜索按钮配置" key="1">
                        <LegionsProForm <PropertyQuerySearchFields>
                            InputDataModel={PropertyQuerySearchFields}
                            mapPropsToFields={(props) => {
                                const initOnSearch = { onQuerySearch: null,onQueryReset: null,};
                                ['onQueryReset','onQuerySearch'].map((item) => {
                                    if (!props[item]['value']) {
                                        props[item]['value'] = TableListViewDomain.tableAutoQuerystaticMember[item]['value'];
                                        initOnSearch[item]=this.execcodeast('onQuerySearch', props[item]['value'])
                                    }
                                })
                                if (initOnSearch.onQueryReset && initOnSearch.onQuerySearch) {
                                    QueryPropertyApp.queryComponentRef.methods.setFieldsValues('search',(value) => {
                                        //@ts-ignore
                                        value.conditionsProps['onReset'] = initOnSearch.onQueryReset;
                                        value.conditionsProps['onResetExec'] = props['onQueryReset']['value'];
                                        value.conditionsProps['onSearchExec'] = props['onQuerySearch']['value'];
                                        value.conditionsProps['onSearch'] = initOnSearch.onQuerySearch;
                                    })
                                }
                                return new PropertyQuerySearchFields(props); // 实际处理结果实体
                            }}
                            onFieldsChange={(props,formFields) => {
                                QueryPropertyApp.querySearchFormProperyRef.store.updateFormInputData(QueryPropertyApp.querySearchFormProperyRef.uid,formFields);
                            }}
                            onReady={(form,ref) => {
                                QueryPropertyApp.querySearchFormProperyRef = { ...ref,that: this };
                            }}
                            colCount={1}
                            controls={this.createQuerySearchPropertyConfig()}
                        ></LegionsProForm>
                    </Panel>
                    <Panel header="组件属性" key="2">
                       
                        <LegionsProForm
                            <PropertyQueryFormFields>
                            InputDataModel={PropertyQueryFormFields}
                            mapPropsToFields={(props) => {
                                return new PropertyQueryFormFields(props); // 实际处理结果实体
                            }}
                            onFieldsChange={(props,formFields) => {
                                QueryPropertyApp.queryConditionsFormProperyRef.store.updateFormInputData(QueryPropertyApp.queryConditionsFormProperyRef.uid,formFields);
                            }}
                            onReady={(form,ref) => {
                                QueryPropertyApp.queryConditionsFormProperyRef = { ...ref,that: this };
                            }}
                            colCount={1}
                            controls={this.createQueryConditionsPropertyConfig()}
                        ></LegionsProForm>
                    </Panel>
                </Collapse>
                <AddSelectOptions
                    onOkSave={(values) => {
                        const componentActiveType = QueryPropertyApp.viewModel.componentActiveType;
                        if (values && values.type === 'local') {
                            runInAction(() => {
                                if (componentActiveType === 'select') {
                                    QueryPropertyApp.queryComponentRef.methods.setFieldsValues<InstanceType<typeof LegionsProConditions['ConditionSelectModel']>>(QueryPropertyApp.editUid,(value) => {
                                        value.conditionsProps.options = [...values.data];
                                    })
                                }
                                if (componentActiveType === 'radioButton') {
                                    QueryPropertyApp.queryComponentRef.methods.setFieldsValues<InstanceType<typeof LegionsProConditions['ConditionRadioButtonModel']>>(QueryPropertyApp.editUid,(value) => {
                                        value.conditionsProps.options = [...values.data.map((item) => {
                                            return {
                                                value: item.key,
                                                label: item.value,
                                            }
                                        })]
                                    })
                                }
                            })
                        }
                        if (values && values.type === 'remote') {
                            const projectCommonApp = this.props.store.context.projectCommonApp;
                            
                            //@ts-ignore
                            const autoQuery = {};
                            ['isRemote','isPageing','ApiUrl','token','method','params','transform','mappingEntity'].map((m) => {
                                let mappName = m;
                                if(m==='ApiUrl'){
                                    mappName='apiUrl'
                                }
                                const value = projectCommonApp.getAddSelectValueFormPropertyValue(mappName);
                                autoQuery[m] = value;
                            })
                            projectCommonApp.updateSelectValue('remote',{
                                //@ts-ignore
                                remote: autoQuery,
                            });
                            const receiveValue = 'this.props.store.context.listPagePropertyApp.context.TablePropertyApp';
                            const execcodeast = (name:string) => {
                                const code= transformFuncToExeccodeast(autoQuery[name],{
                                    propertyName: name,
                                    receiveValue: `${receiveValue}.viewModel.paramesExeccodeast`,
                                });
                                eval(getExecutableScript(code,this));
                                return TablePropertyApp.viewModel.paramesExeccodeast[name]
                            }
                            QueryPropertyApp.queryComponentRef.methods.setFieldsValues<InstanceType<typeof LegionsProConditions['ConditionSelectModel']>>(projectCommonApp.editComponentUid,(value) => {
                                //@ts-ignore   业务场景需要，正常情况下不建议动态变更只读属性值
                                value.conditionsProps['autoQuery'] = {};
                                value.conditionsProps['autoQuery'].ApiUrl = autoQuery['ApiUrl'];
                                value.conditionsProps['autoQuery'].params = execcodeast('params');
                                value.conditionsProps['autoQuery'].transform = execcodeast('transform');
                                value.conditionsProps['autoQuery'].mappingEntity = execcodeast('mappingEntity');
                                value.conditionsProps['autoQuery'].method = autoQuery['method'];
                                value.conditionsProps['autoQuery'].token = execcodeast('token');
                                value.conditionsProps.options = [];
                                
                                if (has(autoQuery,'isRemote')) {
                                    value.conditionsProps.remote = autoQuery['isRemote']
                                }
                                if (has(autoQuery,'isPageing')) {
                                    value.conditionsProps.paging = autoQuery['isPageing']
                                }
                            })
                        }
                    }}
                    ></AddSelectOptions>
                
                <LegionsProModal
                    onOk={() => {
                        this.updateTableCodeValue(this.code);
                        this.codeModalRef.viewModel.visible = false;
                    }}
                    onReady={(value) => {
                    this.codeModalRef = value;
                }}>
                    <CodeEditor
                    width="100%"
                    height="300px"
                    mode="typescript"
                    value={this.code}
                    onChange={(values: string) => {
                        this.updateTableCodeValue(values);
                        runInAction(() => {
                            this.code = values;
                        })
                    }}
                ></CodeEditor>
                </LegionsProModal>
            </div>
        )
    }
}